var host = location.origin;
var map = new Map();
window.onload = webSocket;
window.onbeforeunload = closeWebSocket;
var openVideo = false;
var isTimeout = false;
function BrowserType() {
    var userAgent = navigator.userAgent;
    if (userAgent.indexOf("Firefox") > -1)
        return "Firefox";
    if (userAgent.indexOf("Chrome") > -1)
        return "Chrome";
    return "IE";
}

function IsIE() {
    if (BrowserType() == "IE")
        return true;
    else
        return false;
}

// 建立webSocket连接
function webSocket() {
    if (location.origin == undefined) {
        if (!window.location.origin) {
            window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
        }
    }
    if ("WebSocket" in window) {
        websocket = new WebSocket("ws://127.0.0.1:8802");
    } else {
        alert("浏览器不支持");
    }
    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        if (IsIE()) {
            $("#papersVideo").remove();
            $("#videoImg").remove();
            $("#papersImg").remove();
        } else {
            $("#EScanner").remove();
        }
        console.log("socket连接已建立");
        // 获取设备型号
        if (websocket.readyState == 1)
            sendMessage('{"typeName":"GetDeviceName"}');
    };
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var obj = JSON.parse(event.data);
        if ("SignBase64" == obj.typeName) {
            map.set(obj.message.NO, obj.message.Content);
            if (map.size == obj.message.Count) {
                var signImgBase64 = "";
                for (i = 1; i <= map.size; i++) {
                    signImgBase64 += map.get(i);
                }
                $("#signImg").attr('height', 'auto');
                $("#signImg").attr('src', 'data:image/png;base64,' + signImgBase64);
                $("#signBase64").html(signImgBase64);
                $("#beginSign").attr("disabled", false);
                $("#beginSign").attr("style", "");
                $("#readID").attr("disabled", false);
                $("#readID").attr("style", "");
                map = new Map();
            }
        } else if ("IDCardInfo" == obj.typeName) {
            document.getElementById("name").innerHTML = obj.message["Name"];
            document.getElementById("gender").innerHTML = obj.message["Sex"];
            document.getElementById("nation").innerHTML = obj.message["Nation"];
            document.getElementById("year").innerHTML = obj.message["Birthday"].substr(0, 4);
            document.getElementById("month").innerHTML = obj.message["Birthday"].substr(4, 2);
            document.getElementById("day").innerHTML = obj.message["Birthday"].substr(6, 2);
            document.getElementById("address").innerHTML = obj.message["Address"];
            document.getElementById("cardno").innerHTML = obj.message["ID"];
            document.getElementById("authority").innerHTML = obj.message["Department"];
            document.getElementById("periodBegin").innerHTML = obj.message["StartDate"];
            document.getElementById("periodEnd").innerHTML = obj.message["EndDate"];
            var myImage = document.getElementById("cardImg");
            myImage.src = "data:image/bmp;base64," + obj.message["PhotoData"];


        } else if ("PhotoBase64" == obj.typeName) { // 图片信息
            //map.set(obj.message.NO, obj.message.Content);
            //if (map.size == obj.message.Count) {
            //    var base = "";
            //    for (var i = 1; i <= map.size; i++) {
            //        base += map.get(i);
            //    }
            //    var myImage = document.getElementById("cardImg");
            //    myImage.src = "data:image/bmp;base64," + base;
            //    map = new Map();
            //}
        }
        else if ("VideoCapBase64" == obj.typeName) { // 预览

           

            //map.set(obj.message.NO,obj.message.Content);
            //if(map.size == obj.message.Count){
            //	var base = "";
            //	for(var i=1;i<=map.size;i++){
            //		base += map.get(i);
            //	}
            if (timestamp == obj.flag && openVideo) {
                var videoImg = document.getElementById("videoImg");
                videoImg.src = "data:image/bmp;base64," + obj.message;
            } else {
                if (!isTimeout) {
                    isTimeout = true;
                    setTimeout(function () { openVideo = true }, 700);
                }
            }
            //map = new Map();

        } else if ("PhotographBase64" == obj.typeName) { // 拍照结果
            map.set(obj.message.NO, obj.message.Content);
            if (map.size == obj.message.Count) {
                var base = "";
                for (var i = 1; i <= map.size; i++) {
                    base += map.get(i);
                }
                var img = document.getElementById("img");
                if ((x / 90) % 2 != 0) {
                    img.style.width = "auto";
                    img.style.height = "261px;";
                }
                img.src = "data:image/bmp;base64," + base;
                map = new Map();
            }
        }
        else if ("DeviceName" == obj.typeName) {
            $("#DeviceInfo").attr("value", obj.message);  // 设备型号：VID_0B57&PID_9001或VID_31A9&PID_1010或""   空表示设备和程序不匹配
        } else if ("Error" == obj.typeName) {
            alert("错误代码：" + obj.message);  // UPE101 表示未成功连接设备
            window.close();
        }
    };

    //连接关闭的回调方法
    websocket.onclose = function (e) {
        webSocket();
    };

    webSocket.onerror = function (e) {
        console.log(e);
    }
};

// 给服务端发送消息
function sendMessage(message) {
    if (null != websocket)
        websocket.send(message);
}
/**
*签字/重签
*/
var signStart = false;
function beginSignClick() {
    $("#beginSign").attr("style", "background: #888888;border: 1px solid #888888;");
    $("#beginSign").attr("disabled", "disabled");//禁用input标签
    $("#readID").attr("style", "background: #888888;border: 1px solid #888888;");
    $("#readID").attr("disabled", "disabled");//禁用input标签

    if (!signStart) {
        signStart = true;
        //sendMessage("{'typeName':'SignUrl','message':'"+location.origin+"/demo/app/signDevice.html'}");
        sendMessage('{"typeName":"SignUrl","message":"file:///C:/YFSignIDCardServer/demo/app/signDevice.html"}');
        sendMessage("{'typeName':'Start'}");
        $("#beginSign").attr("value", "重签");
    } else {
        $("#signImg").attr('src', '');
        $("#signBase64").html('');
        sendMessage('{"typeName":"Resign"}');
    }
}

/**
* 签字完成断开连接
*/
function endSignClick() {
    sendMessage('{"typeName":"Close","message":"All"}'); // 关闭连接
    window.location.href = "about:blank";
    window.close();
}
/**
* 开始读取身份证信息
*/
var readIDStart = false;
function readIDClick() {
    if (!readIDStart) {
        readIDStart = true;
        sendMessage('{"typeName":"StartIDCardInfo"}');    //开始读取身份证信息
    } else {
        readIDStart = false;
        sendMessage('{"typeName":"StopIDCardInfo"}');    //开始读取身份证信息
    }
}

/**
* 关闭签字程序
*/
function closeWebSocket() {
    if (IsIE())
        EScanner.StopVideo();
    sendMessage('{"typeName":"Close","message":"All"}'); // 关闭所有连接
}

